import { defineStore } from 'pinia'
import { queryMenu } from '@/api/user'

import {
  transformRoutes,
  treesToFlatWithPath,
  addPathToTrees,
  findFirstLeafInOrder,
} from '@/utils/routeUtils'
import router from '@/router'

export const useRouterStore = defineStore('router', {
  state() {
    return {
      activeMenu: '',
      isHaveRouter: false, //是否添加过动态路由
      menuList: [], //菜单列表
      menuListNotree: [], //菜单列表 -- 非树形结构
      tabBarList: [], //导航标签
      refreshPage: false, //刷新页面
      pageName: '',
    }
  },

  actions: {
    //提交当前选择tab,做key
    submitPageName(name) {
      this.pageName = name
    },
    //打开新标签页
    addTab(routedata) {
      routedata.menuName =
        !routedata.menuName || routedata.menuName == '' ? '新页面' : routedata.menuName
      routedata.menuUrl = `${routedata.menuUrl}?pageid=${routedata.menuId}`
      routedata.query = {
        ...routedata.query,
        pageid: routedata.menuId,
      }
      this.tabBarList.push(routedata)
      console.log(this.tabBarList, 'this.tabBarList')

      router.push({
        path: routedata.menuUrl,
        query: routedata.query,
      })
    },
    //刷新页面
    refreshMenu() {
      this.refreshPage = true
      setTimeout(() => {
        this.refreshPage = false
      }, 450)
    },
    //历史记录tab数据修改
    updateTabs(path) {
      return new Promise((resolve, reject) => {
        try {
          const firstMenu = findFirstLeafInOrder(this.menuList)
          if (this.tabBarList.length == 0) {
            this.tabBarList.push(firstMenu) //先添加个首页
          }
          const data = this.menuListNotree.find((i) => {
            return i.menuUrl == path
          })
          if (data) {
            if (this.tabBarList.filter((i) => i.menuUrl == data.menuUrl).length == 0) {
              //没有 就添加
              this.tabBarList.push(data)
            }
          }
          resolve()
        } catch {
          reject()
        }
      })
    },
    //删除标签
    removeTabs(menuId, nowTab) {
      return new Promise((resolve, reject) => {
        try {
          let index = 0
          this.tabBarList.forEach((i, ind) => {
            if (i.menuId == menuId) {
              index = ind - 1
              return false
            }
          })
          this.tabBarList = this.tabBarList.filter((i) => i.menuId != menuId)

          resolve(nowTab == menuId ? this.tabBarList[index] : '')
        } catch {
          reject()
        }
      })
    },
    //获取动态路由及菜单
    setRouter() {
      return new Promise((resolve, reject) => {
        queryMenu()
          .then((res) => {
            if (res.rtnCode === '0000') {
              // this.isHaveRouter = true //标记已添加过动态路由
              const dynamicRoutes = transformRoutes(res.body)
              // 找到主路由并添加子路由
              const mainRoute = router.options.routes.find((r) => r.path === '/')
              if (mainRoute) {
                // 先移除可能已存在的动态路由
                mainRoute.children = mainRoute.children.filter((child) => !child.meta?.isDynamic)

                // 添加新的动态路由并标记为动态
                dynamicRoutes.forEach((route) => {
                  route.meta.isDynamic = true
                  mainRoute.children.push(route)
                })

                // 4. 添加404路由
                router.addRoute({
                  path: '/:pathMatch(.*)*',
                  name: 'NotFound',
                  component: () => import('@/views/NotFound.vue'),
                  meta: { noAuth: true },
                })

                // 重新添加主路由以确保更改生效
                router.addRoute(mainRoute)
              }

              const firstMenu = findFirstLeafInOrder(res.body)
              if (firstMenu) {
                this.activeMenu = firstMenu.menuUrl
              }

              this.menuList = addPathToTrees(res.body)
              this.menuListNotree = treesToFlatWithPath(res.body)
              this.isHaveRouter = true //标记已添加过动态路由
              resolve()
            }
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
  },

  getters: {},
})
